<template>
  <div class="new-post-container">
    <div class="post-editor-box">
      <h2>新建博客</h2>

      <form @submit.prevent="savePost">
        <input v-model="title" type="text" placeholder="博客标题" required />
        <div class="font-size-control">
          <label>字体大小：{{ fontSize }}px</label>
          <input type="range" min="12" max="32" v-model.number="fontSize" />
        </div>
        <div class="editor-toolbar">
          <input type="file" accept="image/*" @change="uploadImage" />
          <button type="button" @click="togglePreview">{{ isPreview ? '编辑' : '预览' }}</button>
        </div>

        <!-- 使用 CodeMirror 替代 textarea -->
        <Codemirror
          v-if="!isPreview"
          ref="codemirror" 
          v-model="content"
          :extensions="codemirrorExtensions"
          :options="codemirrorOptions"
          :style="{ fontSize: fontSize + 'px' }"
          />

        <!-- Markdown 预览区域 -->
        <div
          v-else
          class="markdown-preview"
          v-html="renderedContent"
          :style="{ fontSize: fontSize + 'px' }"
        ></div>

        <button v-show="!isPreview" type="submit">保存</button>
      </form>
    </div>
  </div>
</template>

<script>

import axios from 'axios'; // 添加这一行
import { marked } from 'marked';
import hljs from 'highlight.js'; // 用于代码块高亮
import { Codemirror } from 'vue-codemirror';
import { markdown } from '@codemirror/lang-markdown';
import 'highlight.js/styles/github.css';

// 可选：添加默认主题（无需解构导入）
// import { dracula } from '@codemirror/theme-dracula'; // ❌ 删除这一行
marked.setOptions({
  highlight: (code, lang) => {
    return hljs.highlight(code, { language: lang || 'plaintext' }).value;
  },
  langPrefix: 'hljs language-'
});
export default {
  components: {
    Codemirror
  },
  setup() {
    return {
      codemirrorExtensions: [
        markdown(), // 启用 Markdown 语法高亮
      ],
      codemirrorOptions: {
  autofocus: true,
  lineNumbers: true,
  styleActiveLineGutter: true,
  theme: 'dracula' // 字符串方式使用主题名
}
    };
  },
  // 其他 data / computed / methods 不变...
  data() {
  return {
    title: '',
    content: '',
    isPreview: false,
    editorWidth: '70vw',
    editorHeight: '80vh',
    fontSize: 16 // 默认字体大小为 16px
  };
},
  computed: {
    renderedContent() {
      return marked.parse(this.content || '');
    }
  },
  mounted() {
  this.setEditorSize();
  window.addEventListener('resize', this.setEditorSize);
   
  
  
   
},
 updated() {
    this.$nextTick(() => {
      const codeBlocks = document.querySelectorAll('.markdown-preview pre code');
      codeBlocks.forEach(block => {
        hljs.highlightElement(block);
      });
    });
  },
  methods: {
    async savePost() {
  if (!this.title.trim()) {
    alert('请输入博客标题');
    return;
  }

  if (!this.content.trim()) {
    alert('内容不能为空');
    return;
  }

  try {
    const response = await axios.post(
      'http://localhost:8000/api/blog/',
      {
        title: this.title,
        content: this.content
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      }
    );

    console.log('博客保存成功:', response.data);
    alert('博客保存成功');
    this.$router.push('/index'); // 跳转到首页或其他页面
  } catch (err) {
    console.error('保存博客失败:', err);
    alert('保存博客失败，请检查控制台日志');
  }
},
    onTabPress(e) {
    const el = e.target;
    const startPos = el.selectionStart;
    const endPos = el.selectionEnd;
    const value = el.value;

    // 插入 4 个空格
    const tab = '    ';
    this.content = value.substring(0, startPos) + tab + value.substring(endPos);

    // 设置光标位置到插入后的位置
    this.$nextTick(() => {
      el.focus();
      el.setSelectionRange(startPos + tab.length, startPos + tab.length);
    });
  },


    setEditorSize() {
    this.editorWidth = `${window.innerWidth * 0.7}px`;
    this.editorHeight = `${window.innerHeight * 0.8}px`;
  },
    async uploadImage(e) {
  const file = e.target.files[0];
  if (!file) return;

  if (this.isPreview) {
    alert('请先退出预览模式再插入图片');
    return;
  }

  const codemirror = this.$refs.codemirror;
  if (!codemirror) {
    console.error('Codemirror ref is undefined');
    return;
  }

  let retry = 0;
  while (retry < 10) {
    if (this.isPreview) {
    alert('请先退出预览模式再插入图片!!!');
    return;
  }
    console.log(codemirror)
    const editor = codemirror.view;
    if (editor) {
      const { from, to } = editor.state.selection.main;

      // 插入占位符
      editor.dispatch({
        changes: { from, to, insert: "![图片描述](uploading...)" }
      });

      const cursorStart = from;
      const cursorEnd = from + "![图片描述](uploading...)".length;

      const formData = new FormData();
      formData.append('image', file);

      try {
        const res = await axios.post('http://localhost:8000/api/upload-image/', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        });

        const imageUrl = res.data.url;

        // 替换为真实链接
        editor.dispatch({
          changes: { from: cursorStart, to: cursorEnd, insert: `![图片描述](${imageUrl})` }
        });
      } catch (err) {
        // 删除占位符
        editor.dispatch({ changes: { from: cursorStart, to: cursorEnd, insert: '' } });
        alert('图片上传失败');
        console.error('Upload failed:', err);
      }

      break;
    } else {
      await new Promise(resolve => setTimeout(resolve, 50));
      retry++;
    }
  }

  if (retry >= 10) {
    console.error('Editor instance is still undefined after waiting');
  }
},

    insertAtCursor(text) {
  const codemirror = this.$refs.codemirror;

  if (!codemirror) return;

  //  获取 editor 实例方式改变：
  const editor = codemirror.codemirror;

  if (!editor) return;

  //const cursorPos = editor.getDoc().getSelection().from;

  // 插入文本到光标位置
  editor.getDoc().replaceSelection(text);
},

    togglePreview() {
      this.isPreview = !this.isPreview;
    }
  }
};
</script>

 
<style scoped>
.font-size-control {
  margin: 10px 0;
}

.font-size-control input[type="range"] {
  width: 100%;
}
 
.editor-toolbar {
  margin-bottom: 10px;
}
 .markdown-preview {
  border: 1px solid #ccc;
  padding: 10px;
  min-height: 200px;
   background-color: #e6f7ff; /* 淡蓝色背景 */
  white-space: pre-line;
  font-family: sans-serif;
  line-height: 1.2;
  text-align: left; /* 容器默认左对齐 */
}

/* 强制所有子元素左对齐（scoped 生效技巧） */
:deep(.markdown-preview h1),
:deep(.markdown-preview h2),
:deep(.markdown-preview h3),
:deep(.markdown-preview h4),
:deep(.markdown-preview h5),
:deep(.markdown-preview h6),
:deep(.markdown-preview p) {
  text-align: left !important;
  margin-left: 0 !important;
  margin-right: 0 !important;
}

:deep(.markdown-preview pre),
:deep(.markdown-preview code) {
  text-align: left !important;
}
.markdown-preview img {
  max-width: 100%;
  height: auto;
}
</style>
